'use strict';
const BaseController = require('./base');
const serviceName = 'address';
// 继承baseController 并且指定serviceName
class AddressController extends BaseController {
  constructor(ctx) {
    super(ctx, serviceName);
  }

  // 获取当前用户的所有地址
  async getUserAddresses() {
    const { ctx } = this;
    const userId = ctx.query.member_user_id
    if (!userId) {
      ctx.success([])
      return
    }
    const addresses = await ctx.service.address.getUserAddresses(userId);
    ctx.success(addresses);
  }

  // 设置默认地址
  async setDefault() {
    const { ctx } = this;
    const { id, member_user_id } = ctx.request.body;
    if (!member_user_id) {
      ctx.error('请登录', 400);
    }
    if (!id) {
      ctx.error('请提供地址ID', 400);
      return;
    }
    
    await ctx.service.address.setDefault(id, member_user_id);
    ctx.success({ id }, 200);
  }

  // 获取默认地址
  async getDefault(){
    const { ctx } = this;
    const { member_user_id } = ctx.query;
    if (!member_user_id) {
      ctx.success(null);
    }
    const res = await ctx.service.address.getDefault(member_user_id);
    ctx.success(res, 200);
  }
}

module.exports = AddressController;
